package cn.bocweb.spinning.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CollectRemoveBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.SequenceAnswerBean;
import cn.bocweb.spinning.model.Bean.SequenceListBean;
import cn.bocweb.spinning.model.Bean.SequenceSyncBean;
import cn.bocweb.spinning.model.Bean.SequenceSyncForLoginBean;
import cn.bocweb.spinning.model.Bean.SequenceUpdateBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.SequenceTestAdapter;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.SwipeGridView;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.fragment.SequenceTestFragment;
import de.greenrobot.event.EventBus;

public class SequenceTestActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.sequence_detail)
    LinearLayout sequenceDetail;
    @Bind(R.id.sequence_num)
    TextView sequenceNum;
    @Bind(R.id.sequence_count)
    TextView sequenceCount;
    @Bind(R.id.sequence_list)
    LinearLayout sequenceList;
    @Bind(R.id.sequence_cocllect)
    LinearLayout sequenceCocllect;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.sequence_viewpage)
    ViewPager sequenceViewpage;

    boolean isLoadMore;
    boolean collected;
    Map<Integer, SequenceAnswerBean> sequences;
    List<SequenceUpdateBean> sequenceUpdateBeans;
    List<SequenceTestFragment> fragmentCopy;
    TextView examPopupRight;
    TextView examPopupWrong;
    TextView examPopupMiss;
    TextView examPopupMore;
    SequenceTestAdapter sequenceTestAdapter;
    List<SequenceTestFragment> fragments;
    Map<Integer, Boolean> answerMap;
    PopupWindow popupWindow;
    TestListAdapter testListAdapter;
    int size, page = 1, miss, wrong, right, answerWrong, quizCount;
    String userid, libid, json;
    UserPresenter presenter;
    boolean isClickMore = false;
    List<SequenceSyncForLoginBean> sequenceSyncForLoginBeen;
    boolean indexPageMoreOne = false, isSequenceTestCollect = false;
    int backToSequencePage = 0;
    @Bind(R.id.imageview_collect)
    ImageView imageviewCollect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sequence_test);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        sequenceSyncForLoginBeen = new ArrayList<>();
        sequences = new HashMap<>();
        sequenceUpdateBeans = new ArrayList<>();
        fragments = new ArrayList<>();
        fragmentCopy = new ArrayList<>();

        initViewPager();
        initModel();
        initClickBtn();
        initPopupWindow();
        initToolbar();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.SEQUENCE_TEST_SYNC: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                if (userid != null && !userid.isEmpty()) {
                    presenter.sequenceSync(libid, userid, json);
                }
                break;
            }
            case Constant.SEQUENCE_TEST_COLLECT: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                backToSequencePage = sequenceViewpage.getCurrentItem();
                isSequenceTestCollect = true;
                fragments.clear();
                sequenceTestAdapter.notifyDataSetChanged();
                presenter.sequenceList(libid, userid, "49", 1);
                break;
            }
        }
    }

    public void onEventMainThread(CollectRemoveBean bean) {
        if (bean.getReturn_code() == 0) {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
            collected = false;
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    /**
     * 获得题目列表
     */
    public void onEventMainThread(SequenceListBean bean) {
        if (bean.getReturn_code() == 0) {
            if (!isClickMore) {
                for (int i = 0; i < bean.getData().size(); i++) {
                    if (bean.getData().get(i).getDetail() != null) {
                        switch (bean.getData().get(i).getDetail().getIsright()) {
                            case "0": {
                                answerMap.put(i, false);
                                wrong++;
                                break;
                            }
                            case "1": {
                                answerMap.put(i, true);
                                right++;
                                break;
                            }
                        }
                    }
                }
                quizCount = bean.getData().size();

                if (bean.getLast() != null && !bean.getLast().isEmpty()) {
                    int last = Integer.parseInt(bean.getLast());
                    int firstLoadCount;
                    if (last > 49) {
                        firstLoadCount = 49 * (last / 49 + 1);
                    } else {
                        firstLoadCount = 49;
                    }

                    for (int i = 0; i < firstLoadCount; i++) {
                        SequenceTestFragment fragment = new SequenceTestFragment(userid, libid, i);
                        fragment.setUserid(userid);
                        fragmentCopy.add(fragment);
                    }
                } else {
                    for (int i = 0; i < bean.getData().size(); i++) {
                        fragmentCopy.add(new SequenceTestFragment(userid, libid, i));
                    }
                }
                fragments.addAll(fragmentCopy);
                sequenceTestAdapter.notifyDataSetChanged();
                miss = bean.getTotal();
                examPopupMiss.setText(String.valueOf(bean.getTotal() - bean.getRightCount() - bean.getErrorCount()));
                examPopupRight.setText(String.valueOf(bean.getRightCount()));
                examPopupWrong.setText(String.valueOf(bean.getErrorCount()));

                testListAdapter.setSize(bean.getData().size());
                testListAdapter.notifyDataSetChanged();
                sequenceCount.setText(String.valueOf(bean.getTotal()));

                if (!isSequenceTestCollect) {
                    if (bean.getLast() != null && !bean.getLast().isEmpty()) {
                        if (Integer.parseInt(bean.getLast()) != 0) {
                            sequenceViewpage.setCurrentItem(Integer.parseInt(bean.getLast()));
                        } else {
                            sequenceViewpage.setCurrentItem(1);
                            sequenceViewpage.setCurrentItem(0);
                        }
                    } else {
                        sequenceViewpage.setCurrentItem(1);
                        sequenceViewpage.setCurrentItem(0);
                    }
                } else {
                    sequenceViewpage.setCurrentItem(backToSequencePage);
                }
            } else {
                for (int i = 0; i < bean.getData().size(); i++) {
                    if (bean.getData().get(i).getDetail() != null) {
                        switch (bean.getData().get(i).getDetail().getIsright()) {
                            case "0": {
                                answerMap.put(quizCount + i, false);
                                wrong++;
                                break;
                            }
                            case "1": {
                                answerMap.put(quizCount + i, true);
                                right++;
                                break;
                            }
                        }
                    }
                }

                examPopupMiss.setText(String.valueOf(bean.getTotal() - bean.getRightCount() - bean.getErrorCount()));
                examPopupRight.setText(String.valueOf(bean.getRightCount()));
                examPopupWrong.setText(String.valueOf(bean.getErrorCount()));

                for (int i = 0; i < bean.getData().size(); i++) {
                    if (fragments.size() < (i + quizCount + 1)) {
                        fragments.add(new SequenceTestFragment(userid, libid, i + quizCount));
                        DeviceUtil.Log("load more = " + (quizCount + i));
                    }
                }
                quizCount += bean.getData().size();
                examPopupMiss.setText(String.valueOf(miss + bean.getData().size()));
                sequenceTestAdapter.notifyDataSetChanged();
                testListAdapter.setSize(quizCount);
                testListAdapter.notifyDataSetChanged();

                if (isLoadMore) {
                    fragments.get(sequenceViewpage.getCurrentItem()).setVisible(true);
                    isLoadMore = false;
                }
            }
        } else if (bean.getReturn_code() == -203) {
            examPopupMore.setText("已经是最后一页");
        }
        hideLoading();
    }

    public void onEventMainThread(SequenceSyncBean bean) {
        if (bean.getReturn_code() == 0) {
            DeviceUtil.MyToast(this, bean.getMsg());
            isClickMore = true;
            page++;
            presenter.sequenceList(libid, userid, "49", page);
        } else {
            DeviceUtil.Log("bean = " + bean.getReturn_code() + " msg = " + bean.getMsg());
        }
    }

    public void addQuizDetail(SequenceAnswerBean bean, int position) {
        if (position == sequenceViewpage.getCurrentItem()) {
            sequences.put(sequenceViewpage.getCurrentItem(), bean);
        }
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(SequenceTestActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("是否退出答题");
                builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(Constant.SEQUENCE_BACK_MAIN);
                        finish();
                    }
                });
                builder.show();

            }
        });
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(SequenceTestActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否退出答题");
        builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                setResult(Constant.SEQUENCE_BACK_MAIN);
                finish();

            }
        });
        builder.show();
    }

    private void initClickBtn() {
        sequenceList.setOnClickListener(this);
        sequenceCocllect.setOnClickListener(this);
        sequenceDetail.setOnClickListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initModel() {
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        libid = lib.getId();

        presenter = new UserPresenterImp();
        presenter.sequenceList(libid, userid, "49", page);
        showLoading();
    }

    private void initViewPager() {
        sequenceTestAdapter = new SequenceTestAdapter(getSupportFragmentManager(), fragments);
        sequenceViewpage.setAdapter(sequenceTestAdapter);
        sequenceViewpage.setPageTransformer(true, new ZoomOutPageTransformer());
        sequenceViewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                sequenceNum.setText(String.valueOf(position + 1));
                if ((position + 1) % 49 == 0 && fragments.size() == (position + 1)) {
                    loadMore();
                    DeviceUtil.MyToast(SequenceTestActivity.this, "正在获取下一批题目");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public boolean isCollect(boolean isCollect) {
        collected = isCollect;
        if (isCollect) {
            imageviewCollect.setImageResource(R.mipmap.collected);
        } else {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
        }

        return isCollect;
    }

    private void initPopupWindow() {

        answerMap = new HashMap<>();

        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        final SwipeGridView gridView_testList = (SwipeGridView) view.findViewById(R.id.test_list);
        RelativeLayout iv = (RelativeLayout) view.findViewById(R.id.btn_hide);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        testListAdapter = new TestListAdapter(this, size, answerMap, false);

        examPopupRight = (TextView) view.findViewById(R.id.exam_popup_right);
        examPopupWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        examPopupMiss = (TextView) view.findViewById(R.id.exam_popup_miss);
        examPopupMore = (TextView) view.findViewById(R.id.exam_popup_more);
        examPopupMore.setVisibility(View.VISIBLE);
        examPopupMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(userid)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(SequenceTestActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("是否登录(登录后保存题目)");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            for (int i = 0; i < fragments.size(); i++) {
                                if (answerMap.containsKey(i)) {
                                    sequenceSyncForLoginBeen.add(fragments.get(i).getSequenceSyncForLoginBean());
                                }
                            }
                            Gson gson = new Gson();
                            json = gson.toJson(sequenceSyncForLoginBeen);

                            Intent intent = new Intent(SequenceTestActivity.this, LoginAcivity.class);
                            intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.SEQUENCE_TEST_SYNC);
                            startActivityForResult(intent, Constant.SEQUENCE_TEST_SYNC);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                    builder.show();
                } else {
                    isClickMore = true;
                    page++;
                    presenter.sequenceList(libid, userid, "49", page);
                }
            }
        });
        gridView_testList.setAdapter(testListAdapter);

        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        final int toolbarHeight = DeviceUtil.getViewHeight(toolbar);
        /**
         * 安卓5.0以下有个问题就是用gridview的onItemClickListener监听不到item的监听事件.真他妈的奇怪
         */
        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {
            @Override
            public void click(int position) {
                sequenceViewpage.setCurrentItem(position);
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, screenHeightPx - navigationHeight - toolbarHeight);
        popupWindow.setAnimationStyle(R.style.test_list);

    }

    public void addQuizCorrect(String ttype, String tid, String choose, boolean isCurrent, int position) {

        SequenceUpdateBean bean = new SequenceUpdateBean();
        bean.setTtype(ttype);
        bean.setTid(tid);
        bean.setChoose(choose);
        bean.setCount(String.valueOf(position + 1));
        if (isCurrent) {
            bean.setIsright("1");
        } else {
            bean.setIsright("0");
        }
        sequenceUpdateBeans.add(bean);

        answerMap.put(position, isCurrent);
        if (!isCurrent) {
            wrong = wrong + 1;
            examPopupWrong.setText(String.valueOf(wrong));
            answerWrong++;
        } else {
            right = right + 1;
            examPopupRight.setText(String.valueOf(right));
        }
        miss -= 1;
        examPopupMiss.setText(String.valueOf(miss));
    }

    public void selectRightAnswer(final int page) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sequenceViewpage.setCurrentItem(page);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sequence_list: {
                popupWindow.showAtLocation(sequenceCocllect, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.sequence_cocllect: {
                if (userid == null || userid.isEmpty()) {
                    Intent intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.SEQUENCE_TEST_COLLECT);
                    startActivityForResult(intent, Constant.SEQUENCE_TEST_COLLECT);
                } else {
                    if (collected) {
                        presenter.collectRemove(libid, userid, "2", fragments.get(sequenceViewpage.getCurrentItem()).getTid(), fragments.get(sequenceViewpage.getCurrentItem()).getTtype());
                    } else {
                        fragments.get(sequenceViewpage.getCurrentItem()).setCollect(sequenceViewpage.getCurrentItem());
                    }
                }
                break;
            }
            case R.id.sequence_detail: {
                if (fragments.size() > 0) {
                    fragments.get(sequenceViewpage.getCurrentItem()).showDetail();
                }
                break;
            }
        }
    }

    public void loadMore() {
            isClickMore = true;
            isLoadMore = true;
            page++;
            presenter.sequenceList(libid, userid, "49", page);
    }
}
